package cn.cimoc.config;

import cn.cimoc.constant.ConstantPool;
import cn.cimoc.mapper.PermissionMapper;
import cn.cimoc.mapper.RoleMapper;
import cn.cimoc.model.po.TPermission;
import cn.cimoc.model.po.TRole;
import cn.cimoc.util.RedisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.*;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.stereotype.Component;

import java.util.List;


@Slf4j
@Component
public class ApplicationEventListener implements ApplicationListener<ApplicationEvent> {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;


    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        // 在这里可以监听到Spring Boot的生命周期
        if(event instanceof ApplicationStartingEvent){
            log.info("应用程序启动中");
        } else if (event instanceof ApplicationEnvironmentPreparedEvent) {
            log.info("初始化环境变量");
        } else if (event instanceof ApplicationPreparedEvent) {
            log.info("初始化环境变量完成，初始化上下文context完成");
        } else if (event instanceof ContextRefreshedEvent) {
            log.info("应用刷新");
            // 初始化redis中的权限记录
            QueryWrapper<TRole> wrapper = new QueryWrapper<>();
            wrapper.select("name");
            List<TRole> roles = roleMapper.selectList(wrapper);
            for (TRole role: roles) {
                List<TPermission> permissionByRoleName = permissionMapper.findPermissionByRoleName(role.getName());
                String[] permissions = new String[permissionByRoleName.size()];
                for (int i = 0; i < permissionByRoleName.size(); i++) {
                    permissions[i] = permissionByRoleName.get(i).getValue();
                }
                String permission = String.join(",", permissions);
                redisUtils.set(ConstantPool.ROLE_PREFIX + role.getName(), permission);
            }
        } else if (event instanceof ApplicationReadyEvent) {
            log.info("应用已启动完成");
        } else if (event instanceof ContextStartedEvent) {
            log.info("应用启动好了");
        } else if(event instanceof ApplicationFailedEvent){
            log.info("应用启动失败");
        }else if (event instanceof ContextStoppedEvent) {
            log.info("应用停止");
        } else if (event instanceof ContextClosedEvent) {
            log.info("应用关闭");
        }
    }

}